package com.danielmiller.mygradebook;

import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class AddGrade extends Activity implements OnItemClickListener, OnItemLongClickListener{

	SQLiteDatabase db;
	public int class_index, category_index;
	private ListView listView;
	ArrayList<String> arrayList = new ArrayList<String>();
	String array[] = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addnewitem);

		class_index = getIntent().getIntExtra("CLASS_INDEX", -1);
		category_index = getIntent().getIntExtra("CATEGORY_INDEX", -1);
		
		//Populate List
		db = openOrCreateDatabase(
				"SEMESTER_DB.db"
				, SQLiteDatabase.CREATE_IF_NECESSARY
				, null
		);
		db.setVersion(1);
		db.setLocale(Locale.getDefault());
		db.setLockingEnabled(true);
		
		Cursor cur = db.rawQuery("SELECT grade_name, grade_recv, grade_poss FROM tbl_grades" +
				" WHERE grade_class_id = '" + class_index + "'", null);

		if (cur != null ) {
			if  (cur.moveToFirst()) {
				do {
					String catName = cur.getString(cur.getColumnIndex("category_name"));
					int gradeR = Integer.parseInt(cur.getString(cur.getColumnIndex("grade_recv")));
					int gradeP = Integer.parseInt(cur.getString(cur.getColumnIndex("grade_poss")));
					int gradeO = (gradeR * 100) / gradeP;
					catName = catName + "\t  " + gradeO;
					arrayList.add(catName);
				}while (cur.moveToNext());
			}
		}
		array = arrayList.toArray(array);
		cur.close();
		db.close();

		listView=(ListView)findViewById(R.id.grading_rubric_list_view);
		listView.setOnItemClickListener(this);
		listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , 
				array));

		final Button createButton = (Button) findViewById(R.id.new_item_button);
		createButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(AddGrade.this, AddGradeItem.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra("CLASS_INDEX", class_index);
				intent.putExtra("CATEGORY_INDEX", category_index);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		//QUERY ITEM AND DELETE FROM DATABASE
		return false;
	}
}
